import tkinter as tk
from tkinter import ttk, messagebox, scrolledtext
import datetime
import os
import sys
import json
from pathlib import Path
from typing import List, Dict, Any, Tuple, Optional, Set

# Add project root to system path
current_dir = os.path.dirname(os.path.abspath(__file__))
project_root = os.path.abspath(os.path.join(current_dir, ".."))
sys.path.append(project_root)

# System imports
from User.Student import Student
from User.Teacher import Teacher
from User.Manager import Manager
from System.UserSystem import UserSystem
from System.CourseSystem import CourseSystem
from System.AssignmentSystem import AssignmentSystem
from Course.Course import Course

def SetupStyle():
    style = ttk.Style()
    style.configure("Main.TFrame", background="#ffffff")
    style.configure("Card.TFrame", background="#ffffff", borderwidth=1, relief="solid")
    style.configure("Accent.TButton", background="#4CAF50", foreground="#4CAF50", font=("Arial", 10, "bold"), padding=10)
    style.map("Accent.TButton", background=[("active", "#45a049")], foreground=[("active", "white")])
    style.configure("Primary.TButton", background="#096BFF", foreground="#0890E5", font=("Arial", 10, "bold"), padding=8)
    style.map("Primary.TButton", background=[("active", "#fdfdfd")], foreground=[("active","#2F5580" )])
    style.configure("Title.TLabel", font=("Arial", 14, "bold"), background="#ffffff", foreground="#2F5580")
    style.configure("SubTitle.TLabel", font=("Arial", 12, "bold"), background="#ffffff", foreground="#333333")
    style.configure("Normal.TLabel", font=("Arial", 10), background="white", foreground="#555555")
    style.configure("TEntry", font=("Arial", 10), padding=8, borderwidth=1, relief="solid")
    style.configure("Treeview.Heading", font=("Arial", 10, "bold"), background="#2F5580", foreground="white")
    style.configure("Treeview", font=("Arial", 9), rowheight=25)

class AssignmentSubmissionWindow(tk.Toplevel):
    """Student assignment submission viewing and grading window - all time dependencies removed"""
    def __init__(self, parent: tk.Tk, assignment_id: str, course: Course, teacher: Teacher, user_system: UserSystem, assignment_system: AssignmentSystem, course_system: CourseSystem):
        super().__init__(parent)
        self.title(f"Assignment Submission Management")
        self.geometry("900x600")
        self.resizable(True, True)
        
        self.assignment = assignment_system.get_assignment_by_id(assignment_id)
        self.course = course
        self.teacher = teacher
        self.user_system = user_system
        self.assignment_system = assignment_system
        self.course_system = course_system
        
        if not self.assignment:
            messagebox.showerror("Error", f"Assignment with ID {assignment_id} not found")
            self.destroy()
            return
            
        self.title(f"Assignment Submission Management - {self.assignment.Title}")
        
        # Main frame using grid layout to ensure button area visibility
        main_frame = ttk.Frame(self, style="Main.TFrame", padding=10)
        main_frame.pack(fill=tk.BOTH, expand=True)
        main_frame.grid_rowconfigure(0, weight=1)
        main_frame.grid_columnconfigure(1, weight=1)
        
        # Left student list
        left_frame = ttk.Frame(main_frame, width=300)
        left_frame.grid(row=0, column=0, sticky="nsw", padx=(0, 15), pady=5)
        
        ttk.Label(left_frame, text="Student List", style="SubTitle.TLabel").pack(anchor=tk.W, pady=(0, 10))
        
        # Student list treeview
        self.student_tree = ttk.Treeview(
            left_frame, columns=("student_id", "student_name", "status", "grade"), show="headings", height=18
        )
        self.student_tree.heading("student_id", text="Student ID")
        self.student_tree.heading("student_name", text="Student Name")
        self.student_tree.heading("status", text="Submission Status")
        self.student_tree.heading("grade", text="Grade")
        
        self.student_tree.column("student_id", width=80, anchor=tk.CENTER)
        self.student_tree.column("student_name", width=100, anchor=tk.CENTER)
        self.student_tree.column("status", width=80, anchor=tk.CENTER)
        self.student_tree.column("grade", width=40, anchor=tk.CENTER)
        
        tree_scroll = ttk.Scrollbar(left_frame, orient="vertical", command=self.student_tree.yview)
        self.student_tree.configure(yscroll=tree_scroll.set)
        self.student_tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        tree_scroll.pack(side=tk.RIGHT, fill=tk.Y)
        
        self.student_tree.bind("<<TreeviewSelect>>", self._on_student_select)
        
        # Right content area
        right_frame = ttk.Frame(main_frame)
        right_frame.grid(row=0, column=1, sticky="nsew", pady=5)
        right_frame.grid_rowconfigure(0, weight=1)
        right_frame.grid_rowconfigure(1, weight=0)
        right_frame.grid_columnconfigure(0, weight=1)
        
        # Assignment content area - removed submission time display
        content_frame = ttk.LabelFrame(right_frame, text="Assignment Content", padding=10)
        content_frame.grid(row=0, column=0, sticky="nsew", pady=(0, 15))
        
        self.content_text = scrolledtext.ScrolledText(content_frame, wrap=tk.WORD, state=tk.DISABLED, font=("SimHei", 10))
        self.content_text.pack(fill=tk.BOTH, expand=True)
        
        # Grading area
        grade_frame = ttk.LabelFrame(right_frame, text="Grading", padding=10)
        grade_frame.grid(row=1, column=0, sticky="nsew", pady=(0, 10))
        grade_frame.grid_rowconfigure(1, weight=1)
        grade_frame.grid_columnconfigure(1, weight=1)
        
        # Score input
        ttk.Label(grade_frame, text="Score:", font=("SimHei", 10)).grid(row=0, column=0, sticky=tk.W, padx=5, pady=5)
        self.grade_entry = ttk.Entry(grade_frame, width=15, font=("SimHei", 10))
        self.grade_entry.grid(row=0, column=1, sticky=tk.W, padx=5, pady=5)
        
        # Feedback area
        ttk.Label(grade_frame, text="Feedback:", font=("SimHei", 10)).grid(row=1, column=0, sticky=tk.NW, padx=5, pady=5)
        self.feedback_text = scrolledtext.ScrolledText(grade_frame, wrap=tk.WORD, height=6, font=("SimHei", 10))
        self.feedback_text.grid(row=1, column=1, sticky="nsew", padx=5, pady=5)
        
        # Button area
        btn_frame = ttk.Frame(right_frame)
        btn_frame.grid(row=2, column=0, sticky="e", pady=10)
        
        self.save_grade_btn = ttk.Button(
            btn_frame, text="Save Grade", command=self._save_grade, style="Accent.TButton", width=15
        )
        self.save_grade_btn.pack(side=tk.RIGHT, padx=5, pady=5)
        
        # Load student data
        self._load_students()
        
        # Currently selected student and submission
        self.current_student = None
        self.current_submission = None
        
        # Disable grading button by default
        self.save_grade_btn.config(state=tk.DISABLED)

    def _load_students(self):
        """Load course students and submission status"""
        for item in self.student_tree.get_children():
            self.student_tree.delete(item)
            
        self.course.Students = self.course_system.GetStudentsInCourse(self.course.ID)
        
        if not hasattr(self.course, 'Students'):
            self.course.Students = []
            messagebox.showwarning("Data Warning", "Course student data not initialized, empty list created automatically")
            
        for student_id in self.course.Students:
            student_id = str(student_id).strip()
            if not student_id:
                continue
                
            student = self.user_system.get_user_by_id(student_id)
            if student:
                submission_found = False
                
                # Directly iterate to find submission records
                if hasattr(self.assignment, 'submissions'):
                    for submission in self.assignment.submissions:
                        if isinstance(submission, dict):
                            sub_student_id = submission.get('student_id')
                        else:
                            sub_student_id = submission.student_id if hasattr(submission, 'student_id') else None
                            
                        if sub_student_id == student.ID:
                            submission_found = True
                            break
                            
                if not submission_found:
                    all_submissions = self.assignment_system.get_submissions_by_assignment(self.assignment.ID)
                    for submission in all_submissions:
                        if isinstance(submission, dict):
                            sub_student_id = submission.get('student_id')
                        else:
                            sub_student_id = submission.student_id if hasattr(submission, 'student_id') else None
                            
                        if sub_student_id == student.ID:
                            submission_found = True
                            break
                            
                grade = ""
                if submission_found:
                    # Directly find grade
                    submission = None
                    if hasattr(self.assignment, 'submissions'):
                        for sub in self.assignment.submissions:
                            if isinstance(sub, dict) and sub.get('student_id') == student.ID:
                                submission = sub
                                break
                            elif not isinstance(sub, dict) and hasattr(sub, 'student_id') and sub.student_id == student.ID:
                                submission = sub
                                break
                                
                    if submission:
                        if isinstance(submission, dict):
                            grade = submission.get('grade', "")
                        else:
                            grade = submission.grade if hasattr(submission, 'grade') and submission.grade is not None else ""
                            
                self.student_tree.insert("", tk.END, values=(
                    student.ID,
                    student.EnglishName,
                    "Submitted" if submission_found else "Not Submitted",
                    grade
                ), tags=(student.ID,))

    def _on_student_select(self, event):
        """Handle student selection event"""
        selected_items = self.student_tree.selection()
        if not selected_items:
            self.save_grade_btn.config(state=tk.DISABLED)
            return
            
        item_id = selected_items[0]
        student_id = self.student_tree.item(item_id, "tags")[0]
        self.current_student = self.user_system.get_user_by_id(student_id)
        self.current_submission = None
        
        # Find submission record
        if hasattr(self.assignment, 'submissions'):
            for submission in self.assignment.submissions:
                if isinstance(submission, dict):
                    sub_student_id = submission.get('student_id')
                else:
                    sub_student_id = submission.student_id if hasattr(submission, 'student_id') else None
                    
                if sub_student_id == student_id:
                    self.current_submission = submission
                    break
                    
        if not self.current_submission:
            all_submissions = self.assignment_system.get_submissions_by_assignment(self.assignment.ID)
            for submission in all_submissions:
                if isinstance(submission, dict):
                    sub_student_id = submission.get('student_id')
                else:
                    sub_student_id = submission.student_id if hasattr(submission, 'student_id') else None
                    
                if sub_student_id == student_id:
                    self.current_submission = submission
                    break
                    
        self._update_submission_display()
        
        if self.current_submission:
            self.save_grade_btn.config(state=tk.NORMAL)
        else:
            self.save_grade_btn.config(state=tk.DISABLED)

    def _update_submission_display(self):
        """Update submission content display - no time display"""
        self.content_text.config(state=tk.NORMAL)
        self.content_text.delete("1.0", tk.END)
        self.grade_entry.delete(0, tk.END)
        self.feedback_text.delete("1.0", tk.END)
        
        if self.current_submission:
            try:
                if isinstance(self.current_submission, dict):
                    content = self.current_submission.get('content', 'No submission content')
                    grade = self.current_submission.get('grade', '')
                    feedback = self.current_submission.get('feedback', '')
                else:
                    content = self.current_submission.content if hasattr(self.current_submission, 'content') else 'No submission content'
                    grade = self.current_submission.grade if hasattr(self.current_submission, 'grade') else ''
                    feedback = self.current_submission.feedback if hasattr(self.current_submission, 'feedback') else ''
                    
                self.content_text.insert(tk.END, content)
                if grade:
                    self.grade_entry.insert(0, str(grade))
                if feedback:
                    self.feedback_text.insert(tk.END, feedback)
                    
            except Exception as e:
                print(f"Error displaying submission content: {str(e)}")
                self.content_text.insert(tk.END, f"Error loading submission content: {str(e)}")
                
        self.content_text.config(state=tk.DISABLED)

    def _save_grade(self):
        """Save grade - completely remove time-related processing"""
        if not self.current_submission or not self.current_student:
            messagebox.showwarning("Warning", "No student selected or no submission record")
            return
            
        try:
            grade_text = self.grade_entry.get().strip()
            grade = float(grade_text) if grade_text else None
            feedback = self.feedback_text.get("1.0", tk.END).strip()
            
            # Call grading method without time parameters
            success = self.assignment_system.grade_assignment(
                self.assignment.ID,
                self.current_student.ID,
                grade,
                feedback,
                self.teacher.ID
            )
            
            if success:
                messagebox.showinfo("Success", "Grade saved successfully")
                
                # Update current submission object - no time information
                if isinstance(self.current_submission, dict):
                    self.current_submission['grade'] = grade
                    self.current_submission['feedback'] = feedback
                    self.current_submission['graded_by'] = self.teacher.ID
                    
                    # Remove time-related fields
                    for key in ['graded_at', 'submitted_at']:
                        if key in self.current_submission:
                            del self.current_submission[key]
                else:
                    self.current_submission.grade = grade
                    self.current_submission.feedback = feedback
                    self.current_submission.graded_by = self.teacher.ID
                    
                    # Remove time-related attributes
                    for attr in ['graded_at', 'submitted_at']:
                        if hasattr(self.current_submission, attr):
                            delattr(self.current_submission, attr)
                            
                # Update grade in student list
                for item in self.student_tree.get_children():
                    if self.student_tree.item(item, "tags")[0] == self.current_student.ID:
                        values = list(self.student_tree.item(item, "values"))
                        values[3] = grade if grade is not None else ""
                        self.student_tree.item(item, values=values)
                        break
            else:
                messagebox.showerror("Failed", "Failed to save grade, please try again")
                
        except ValueError:
            messagebox.showerror("Error", "Please enter a valid score")
        except Exception as e:
            error_msg = f"Error saving grade: {str(e)}"
            print(error_msg)
            messagebox.showerror("Error", error_msg)

class TeacherInfoWindow(tk.Toplevel):
    def __init__(self, parent: tk.Tk, teacher: Teacher):
        super().__init__(parent)
        self.title(f"Personal Information - {teacher.ChineseName}")
        self.geometry("450x350")
        self.resizable(False, False)
        
        main_frame = ttk.Frame(self, style="Main.TFrame")
        main_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=20)
        
        title_label = ttk.Label(main_frame, text="Teacher Basic Information", style="SubTitle.TLabel")
        title_label.pack(anchor=tk.W, pady=(0, 15))
        
        info_frame = ttk.Frame(main_frame, style="Card.TFrame")
        info_frame.pack(fill=tk.BOTH, expand=True)
        
        info_rows = [
            ("ChineseName:", teacher.ChineseName),
            ("EnglishName:", teacher.EnglishName),
            ("Teacher ID:", teacher.ID),
            ("Number of Courses:", len(teacher.Courses))
        ]
        
        for i, (label_text, value_text) in enumerate(info_rows):
            ttk.Label(info_frame, text=label_text, font=("Arial", 10, "bold")).grid(
                row=i, column=0, padx=20, pady=10, sticky=tk.W)
            ttk.Label(info_frame, text=value_text, style="Normal.TLabel").grid(
                row=i, column=1, padx=20, pady=10, sticky=tk.W)
                
        info_frame.grid_columnconfigure(1, weight=1)
        
        close_btn = ttk.Button(main_frame, text="Close", style="Primary.TButton", command=self.destroy)
        close_btn.pack(side=tk.RIGHT, padx=10, pady=10)

class CourseDetailWindow(tk.Toplevel):
    def __init__(self, parent: tk.Tk, course: Course, teacher: Teacher, course_system: CourseSystem, user_system: UserSystem, assignment_system: AssignmentSystem):
        super().__init__(parent)
        self.title(f"{course.CourseName} - Course Management")
        self.geometry("800x600")
        self.resizable(False, False)
        
        self.parent = parent
        self.course = course
        self.teacher = teacher
        self.course_system = course_system
        self.user_system = user_system
        self.assignment_system = assignment_system
        
        self._create_widgets()

    def _create_widgets(self):
        main_frame = ttk.Frame(self, style="Main.TFrame")
        main_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=20)
        
        # Course information tabs
        notebook = ttk.Notebook(main_frame)
        notebook.pack(fill=tk.BOTH, expand=True)
        
        # 1. Course basic information tab
        info_frame = ttk.Frame(notebook, style="Main.TFrame")
        notebook.add(info_frame, text="Course Information")
        self._init_info_tab(info_frame)
        
        # 2. Student management tab
        student_frame = ttk.Frame(notebook, style="Main.TFrame")
        notebook.add(student_frame, text="Student Management")
        self._init_student_tab(student_frame)
        
        # 3. Assignment management tab - integrated submission viewing
        assignment_frame = ttk.Frame(notebook, style="Main.TFrame")
        notebook.add(assignment_frame, text="Assignment Management")
        self._init_assignment_tab(assignment_frame)

    def _init_info_tab(self, frame: ttk.Frame):
        """Initialize course information tab, supports editing course content and description"""
        # Course basic information
        info_frame = ttk.Frame(frame, style="Card.TFrame")
        info_frame.pack(fill=tk.X, pady=(0, 15))
        
        # Editable course information fields
        self.course_fields = {
            "course_id": {"label": "Course ID:", "value": self.course.ID, "editable": False},
            "course_name": {"label": "Course Name:", "value": self.course.CourseName, "editable": True},
            "teacher_id": {"label": "Teacher ID:", "value": self.teacher.ID, "editable": False},
            "course_time": {"label": "Class Time:", "value": self.course.CourseTime, "editable": True},
            "classroom": {"label": "Classroom:", "value": self.course.Classroom, "editable": True}
        }
        
        # Create information input boxes
        self.field_entries = {}
        for i, (field, config) in enumerate(self.course_fields.items()):
            ttk.Label(info_frame, text=config["label"], font=("Arial", 10, "bold")).grid(
                row=i, column=0, padx=15, pady=8, sticky=tk.W)
                
            if config["editable"]:
                entry = ttk.Entry(info_frame, width=40)
                entry.insert(0, config["value"])
                entry.grid(row=i, column=1, padx=15, pady=8, sticky=tk.W)
                self.field_entries[field] = entry
            else:
                ttk.Label(info_frame, text=config["value"]).grid(
                    row=i, column=1, padx=15, pady=8, sticky=tk.W)
        
        # Course description (editable)
        intro_frame = ttk.Frame(frame, style="Card.TFrame")
        intro_frame.pack(fill=tk.BOTH, expand=True, pady=(0, 15))
        
        ttk.Label(intro_frame, text="Course Description:", style="SubTitle.TLabel").pack(
            anchor=tk.W, padx=15, pady=10)
            
        self.intro_text = scrolledtext.ScrolledText(
            intro_frame, font=("Arial", 10), wrap=tk.WORD, height=8)
            
        # Load course description
        intro_content = getattr(self.course, "introduction", "")
        self.intro_text.insert(tk.END, intro_content)
        self.intro_text.pack(fill=tk.BOTH, expand=True, padx=15, pady=(0, 10))
        
        # Save button
        btn_frame = ttk.Frame(frame)
        btn_frame.pack(fill=tk.X, anchor='e')
        
        save_btn = ttk.Button(
            btn_frame, text="Save Changes", command=self._save_course_changes, style="Primary.TButton"
        )
        save_btn.pack(side=tk.RIGHT, padx=5)
        
        close_btn = ttk.Button(btn_frame, text="Close", command=self.destroy)
        close_btn.pack(side=tk.RIGHT, padx=5)

    def _init_student_tab(self, frame: ttk.Frame):
        """Initialize student management tab, supports adding/removing students"""
        # Top operation area
        top_frame = ttk.Frame(frame)
        top_frame.pack(fill=tk.X, pady=(0, 15))
        
        # Add student input and button
        ttk.Label(top_frame, text="Student ID:").pack(side=tk.LEFT, padx=5)
        self.student_id_entry = ttk.Entry(top_frame, width=15)
        self.student_id_entry.pack(side=tk.LEFT, padx=5)
        
        add_btn = ttk.Button(
            top_frame, text="Add Student", command=self._add_student_to_course, style="Primary.TButton"
        )
        add_btn.pack(side=tk.LEFT, padx=5)
        
        # Delete button
        self.delete_student_btn = ttk.Button(
            top_frame, text="Remove Selected Student", command=self._remove_selected_student, state=tk.DISABLED
        )
        self.delete_student_btn.pack(side=tk.LEFT, padx=5)
        
        # Student list
        student_frame = ttk.Frame(frame, style="Card.TFrame")
        student_frame.pack(fill=tk.BOTH, expand=True)
        
        # Create student table
        self.student_tree = ttk.Treeview(
            student_frame, columns=("student_id", "student_name"), show="headings"
        )
        self.student_tree.heading("student_id", text="Student ID")
        self.student_tree.heading("student_name", text="Student Name")
        self.student_tree.column("student_id", width=100)
        self.student_tree.column("student_name", width=200)
        
        # Bind selection event
        self.student_tree.bind("<<TreeviewSelect>>", self._on_student_select)
        
        # Scrollbar
        scrollbar = ttk.Scrollbar(student_frame, orient="vertical", command=self.student_tree.yview)
        self.student_tree.configure(yscrollcommand=scrollbar.set)
        self.student_tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        
        # Load student data
        self._load_students()

    def _init_assignment_tab(self, frame: ttk.Frame):
        """Initialize assignment management tab, supports publishing/modifying/deleting assignments and viewing submissions"""
        # Top operation area
        self.top_frame = ttk.Frame(frame)
        self.top_frame.pack(fill=tk.X, pady=(0, 15))
        
        publish_btn = ttk.Button(
            self.top_frame, text="Publish New Assignment", command=self._publish_assignment, style="Primary.TButton"
        )
        publish_btn.pack(side=tk.LEFT, padx=5)
        
        # Management button
        self.manage_assignment_btn = ttk.Button(
            self.top_frame, text="Manage Selected Assignment", command=self._manage_selected_assignment, state=tk.DISABLED
        )
        self.manage_assignment_btn.pack(side=tk.LEFT, padx=5)
        
        # New: View submissions button
        self.view_submissions_btn = ttk.Button(
            self.top_frame, text="View Submissions", command=self._view_submissions, state=tk.DISABLED
        )
        self.view_submissions_btn.pack(side=tk.LEFT, padx=5)
        
        # Assignment list
        assignment_frame = ttk.Frame(frame, style="Card.TFrame")
        assignment_frame.pack(fill=tk.BOTH, expand=True)
        
        # Create assignment table
        self.assignment_tree = ttk.Treeview(
            assignment_frame, columns=("assignment_id", "title", "deadline", "status"), show="headings"
        )
        self.assignment_tree.heading("assignment_id", text="Assignment ID")
        self.assignment_tree.heading("title", text="Assignment Title")
        self.assignment_tree.heading("deadline", text="Deadline")
        self.assignment_tree.heading("status", text="Status")
        
        self.assignment_tree.column("assignment_id", width=80)
        self.assignment_tree.column("title", width=200)
        self.assignment_tree.column("deadline", width=120)
        self.assignment_tree.column("status", width=80)
        
        # Bind selection event - controls all button states
        self.assignment_tree.bind("<<TreeviewSelect>>", self._on_assignment_select)
        
        # Scrollbar
        scrollbar = ttk.Scrollbar(assignment_frame, orient="vertical", command=self.assignment_tree.yview)
        self.assignment_tree.configure(yscrollcommand=scrollbar.set)
        self.assignment_tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        
        # Load assignment data
        self._load_assignments()

    def _save_course_changes(self):
        """Save course information changes, including course description"""
        try:
            # Collect modified course information, including description
            course_changes = {
                "CourseName": self.field_entries["course_name"].get(),
                "CourseTime": self.field_entries["course_time"].get(),
                "Classroom": self.field_entries["classroom"].get(),
                "introduction": self.intro_text.get("1.0", tk.END).strip()  # Add course description
            }
            
            # Call CourseSystem to update course
            success = self.course_system.UpdateCourse(
                course_id=self.course.ID,** course_changes
            )
            
            if success:
                # Update local course object
                for key, value in course_changes.items():
                    setattr(self.course, key, value)
                    
                messagebox.showinfo("Save Successful", "Course information has been updated")
            else:
                messagebox.showerror("Save Failed", "Failed to update course information")
                
        except Exception as e:
            messagebox.showerror("Error", f"Error saving course information: {str(e)}")

    def _on_student_select(self, event):
        """Handle student selection event"""
        selected_items = self.student_tree.selection()
        if len(selected_items) > 0:
            self.delete_student_btn.config(state=tk.NORMAL)
        else:
            self.delete_student_btn.config(state=tk.DISABLED)

    def _remove_selected_student(self):
        """Remove selected student"""
        selected_items = self.student_tree.selection()
        if not selected_items:
            messagebox.showwarning("Prompt", "Please select a student to remove first")
            return
            
        item_id = selected_items[0]
        student_id = self.student_tree.item(item_id, "values")[0]
        student = self.user_system.get_user_by_id(student_id)
        
        if not messagebox.askyesno("Confirm Deletion", f"Are you sure you want to remove student {student.EnglishName if student else student_id} from the course?"):
            return
            
        try:
            success, msg = self.course_system.RemoveStudentFromCourse(
                course_id=self.course.ID, student_id=student_id
            )
            
            if success:
                messagebox.showinfo("Deletion Successful", f"Removed student: {student.EnglishName if student else student_id}")
                if student_id in self.course.Students:
                    self.course.Students.remove(student_id)
                    
                self._load_students()  # Refresh student list
                self.delete_student_btn.config(state=tk.DISABLED)  # Reset button state
            else:
                messagebox.showerror("Deletion Failed", msg)
                
        except Exception as e:
            messagebox.showerror("Error", f"Error removing student: {str(e)}")

    def _view_submissions(self):
        """View assignment submissions - fixed course system parameter passing"""
        selected_items = self.assignment_tree.selection()
        if not selected_items:
            return
            
        item_id = selected_items[0]
        assignment_id = self.assignment_tree.item(item_id, "values")[0]
        assignment = self.assignment_system.get_assignment_by_id(assignment_id)
        
        if assignment:
            # Create assignment submission window with course system parameter
            AssignmentSubmissionWindow(
                self, assignment_id, self.course, self.teacher, self.user_system, self.assignment_system, self.course_system  # Add course system parameter
            )
        else:
            messagebox.showerror("Error", f"Assignment with ID {assignment_id} not found")

    def _on_assignment_select(self, event):
        """Handle assignment selection event - controls all button states"""
        selected_items = self.assignment_tree.selection()
        if len(selected_items) > 0:
            self.manage_assignment_btn.config(state=tk.NORMAL)
            self.view_submissions_btn.config(state=tk.NORMAL)  # Enable view submissions button
        else:
            self.manage_assignment_btn.config(state=tk.DISABLED)
            self.view_submissions_btn.config(state=tk.DISABLED)  # Disable view submissions button

    def _manage_selected_assignment(self):
        """Manage selected assignment"""
        selected_items = self.assignment_tree.selection()
        if not selected_items:
            return
            
        item_id = selected_items[0]
        assignment_id = self.assignment_tree.item(item_id, "values")[0]
        assignment = self.assignment_system.get_assignment_by_id(assignment_id)
        
        if assignment:
            # Assignment management window
            detail_window = tk.Toplevel(self)
            detail_window.title(f"Assignment Management - {assignment.Title}")
            detail_window.geometry("500x400")
            
            ttk.Label(detail_window, text=f"Assignment ID: {assignment.ID}", font=("Arial", 10, "bold")).pack(pady=5, anchor=tk.W, padx=20)
            ttk.Label(detail_window, text=f"Title: {assignment.Title}", font=("Arial", 10, "bold")).pack(pady=5, anchor=tk.W, padx=20)
            ttk.Label(detail_window, text=f"Deadline: {assignment.Deadline.strftime('%Y-%m-%d %H:%M')}", font=("Arial", 10, "bold")).pack(pady=5, anchor=tk.W, padx=20)
            
            ttk.Label(detail_window, text="Assignment Description:", font=("Arial", 10, "bold")).pack(pady=10, anchor=tk.W, padx=20)
            desc_text = scrolledtext.ScrolledText(detail_window, wrap=tk.WORD, height=10)
            desc_text.insert(tk.END, assignment.Description)
            desc_text.pack(fill=tk.BOTH, expand=True, padx=20, pady=5)
            
            ttk.Button(detail_window, text="Close", command=detail_window.destroy).pack(pady=10)
        else:
            messagebox.showerror("Error", f"Assignment with ID {assignment_id} not found")

    def _load_students(self):
        # Clear existing data
        for item in self.student_tree.get_children():
            self.student_tree.delete(item)
            
        self.course.Students = self.course_system.GetStudentsInCourse(self.course.ID)
        
        # Validate course student data
        if not hasattr(self.course, 'Students'):
            self.course.Students = []
            messagebox.showwarning("Data Warning", "Course student data not initialized, empty list created automatically")
            
        # Get and display student information
        student_count = 0
        for student_id in self.course.Students:
            student_id = str(student_id).strip()
            if not student_id:
                continue
                
            student = self.user_system.get_user_by_id(student_id)
            if student:
                student_count += 1
                self.student_tree.insert("", tk.END, values=(
                    student.ID,
                    student.EnglishName
                ))

    def _load_assignments(self):
        """Load course assignment list from assignment system"""
        # Clear existing data
        for item in self.assignment_tree.get_children():
            self.assignment_tree.delete(item)
            
        # Validate course object and assignment system
        if not hasattr(self, 'assignment_system') or not self.assignment_system:
            self.assignment_tree.insert("", tk.END, values=("", "Assignment system not initialized", "", "Error"))
            return
            
        if not self.course or not hasattr(self.course, 'ID'):
            self.assignment_tree.insert("", tk.END, values=("", "Invalid course object", "", "Error"))
            return
            
        try:
            # Get all assignments for this course from assignment system
            assignments = self.assignment_system.get_assignments_by_course(self.course.ID)
            
            if not assignments:
                self.assignment_tree.insert("", tk.END, values=("", "No assignments for this course yet", "", "Prompt"))
                return
                
            # Sort by deadline (most recent first)
            assignments.sort(key=lambda a: a.Deadline)
            
            # Insert assignment data to UI
            for assignment in assignments:
                status = "Not Due" if assignment.Deadline > datetime.datetime.now() else "Due"
                self.assignment_tree.insert("", tk.END, values=(
                    assignment.ID,
                    assignment.Title,
                    assignment.Deadline.strftime("%Y-%m-%d %H:%M"),
                    status
                ))
                
        except Exception as e:
            self.assignment_tree.insert("", tk.END, values=("", f"Load failed: {str(e)}", "", "Error"))

    def _add_student_to_course(self):
        """Add student to course"""
        student_id = self.student_id_entry.get().strip()
        if not student_id:
            messagebox.showwarning("Prompt", "Please enter a student ID")
            return
            
        # Verify student exists
        student = self.user_system.get_user_by_id(student_id, role_filter=["Student"])
        if not student:
            messagebox.showerror("Error", f"Student ID {student_id} does not exist or is not a student role")
            return
            
        # Verify student not already in course
        if student_id in self.course.Students:
            messagebox.showwarning("Prompt", f"Student {student.EnglishName} is already in the course")
            return
            
        # Add student to course
        try:
            success = self.course_system.AddStudentToCourse(
                course_id=self.course.ID, student_id=student_id
            )
            
            if success:
                messagebox.showinfo("Add Successful", f"Added student: {student.EnglishName}")
                self.course.Students.append(student_id)
                self._load_students()  # Refresh student list
                self.student_id_entry.delete(0, tk.END)
            else:
                messagebox.showerror("Add Failed")
                
        except Exception as e:
            messagebox.showerror("Error", f"Error adding student: {str(e)}")

    def _publish_assignment(self):
        """Publish new assignment"""
        # Create assignment publishing window
        publish_window = tk.Toplevel(self)
        publish_window.title("Publish New Assignment")
        publish_window.geometry("500x400")
        publish_window.resizable(False, False)
        
        # Assignment form
        form_frame = ttk.Frame(publish_window, padding="20")
        form_frame.pack(fill=tk.BOTH, expand=True)
        
        # Assignment title
        ttk.Label(form_frame, text="Assignment Title:").grid(row=0, column=0, sticky=tk.W, pady=10)
        title_entry = ttk.Entry(form_frame, width=40)
        title_entry.grid(row=0, column=1, pady=10)
        
        # Deadline
        ttk.Label(form_frame, text="Deadline:").grid(row=1, column=0, sticky=tk.W, pady=10)
        deadline_entry = ttk.Entry(form_frame, width=40)
        deadline_entry.insert(0, datetime.date.today().strftime("%Y-%m-%d"))
        deadline_entry.grid(row=1, column=1, pady=10)
        
        # Assignment requirements
        ttk.Label(form_frame, text="Assignment Requirements:").grid(row=2, column=0, sticky=tk.NW, pady=10)
        self.assignment_text = scrolledtext.ScrolledText(
            form_frame, font=("Arial", 10), wrap=tk.WORD, height=8, width=40)
        self.assignment_text.grid(row=2, column=1, pady=10)
        
        # Button area
        btn_frame = ttk.Frame(publish_window)
        btn_frame.pack(fill=tk.X, pady=10)
        
        ttk.Button(btn_frame, text="Publish", command=lambda: self._save_assignment(publish_window, title_entry, deadline_entry)).pack(side=tk.RIGHT, padx=5)
        ttk.Button(btn_frame, text="Cancel", command=publish_window.destroy).pack(side=tk.RIGHT, padx=5)

    def _save_assignment(self, window, title_entry, deadline_entry):
        """Save newly published assignment"""
        title = title_entry.get().strip()
        deadline = deadline_entry.get().strip()
        content = self.assignment_text.get("1.0", tk.END).strip()
        
        if not (title and deadline and content):
            messagebox.showerror("Error", "Please fill in all assignment information")
            return
            
        # Validate date format
        try:
            deadline_date = datetime.datetime.strptime(deadline, "%Y-%m-%d")
        except ValueError:
            messagebox.showerror("Error", "Invalid date format, should be YYYY-MM-DD")
            return
            
        # Create assignment
        success, msg = self.assignment_system.create_assignment(
            title=title,
            description=content,
            deadline=deadline_date,
            course_id=self.course.ID
        )
        
        if success:
            self.course.Assignments.append(self.assignment_system.get_assignment_by_id(msg.split(": ")[-1]).ID)
            self.course_system.UpdateCourse(course_id=self.course.ID, Assignments=self.course.Assignments)
            messagebox.showinfo("Publish Successful", msg)
            window.destroy()
            self._load_assignments()
        else:
            messagebox.showerror("Publish Failed", msg)

class TeacherCourseModuleFrame(ttk.Frame):
    def __init__(self, parent: tk.Tk, app: "LMSApp", teacher: Teacher, user_system: UserSystem, course_system: CourseSystem, assignment_system: AssignmentSystem):
        super().__init__(parent, style="Main.TFrame")
        self.app = app
        self.teacher = teacher
        self.user_system = user_system
        self.course_system = course_system
        self.assignment_system = assignment_system
        self.parent = parent
        
        self.parent.geometry("1000x600")
        
        # Back button
        back_btn = ttk.Button(self, text="Return to Main Interface", command=self.back_to_main)
        back_btn.pack(anchor=tk.W, padx=20, pady=10)
        
        # Title
        title_label = ttk.Label(self, text="My Course Management", style="Title.TLabel")
        title_label.pack(anchor=tk.W, padx=20, pady=10)
        
        # Create course button
        create_btn = ttk.Button(
            self, text="Create New Course", command=self._create_new_course, style="Primary.TButton"
        )
        create_btn.pack(anchor=tk.W, padx=20, pady=(0, 10))
        
        # Course list
        self.course_frame = ttk.Frame(self)
        self.course_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=10)
        
        # Create course table
        self.course_tree = ttk.Treeview(
            self.course_frame, columns=("courseId", "courseName", "courseTime", "classroom", "studentCount"), show="headings"
        )
        self.course_tree.heading("courseId", text="Course ID")
        self.course_tree.heading("courseName", text="Course Name")
        self.course_tree.heading("courseTime", text="Class Time")
        self.course_tree.heading("classroom", text="Classroom")
        self.course_tree.heading("studentCount", text="Student Count")
        
        self.course_tree.column("courseId", width=100)
        self.course_tree.column("courseName", width=180)
        self.course_tree.column("courseTime", width=150)
        self.course_tree.column("classroom", width=120)
        self.course_tree.column("studentCount", width=100)
        
        # Add top operation buttons
        course_action_frame = ttk.Frame(self.course_frame)
        course_action_frame.pack(fill=tk.X, pady=(0, 10))
        
        self.manage_course_btn = ttk.Button(
            course_action_frame, text="Manage Selected Course", command=self._manage_selected_course, state=tk.DISABLED
        )
        self.manage_course_btn.pack(side=tk.LEFT, padx=5)
        
        self.delete_course_btn = ttk.Button(
            course_action_frame, text="Delete Selected Course", command=self._delete_selected_course, state=tk.DISABLED
        )
        self.delete_course_btn.pack(side=tk.LEFT, padx=5)
        
        # Scrollbar
        scrollbar = ttk.Scrollbar(
            self.course_frame, orient=tk.VERTICAL, command=self.course_tree.yview
        )
        self.course_tree.configure(yscrollcommand=scrollbar.set)
        self.course_tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        
        # Bind selection event
        self.course_tree.bind("<<TreeviewSelect>>", self._on_course_select)
        
        # Load course data
        self.refresh_courses()

    def _on_course_select(self, event):
        """Handle course selection event"""
        selected_items = self.course_tree.selection()
        if len(selected_items) > 0:
            self.manage_course_btn.config(state=tk.NORMAL)
            self.delete_course_btn.config(state=tk.NORMAL)
        else:
            self.manage_course_btn.config(state=tk.DISABLED)
            self.delete_course_btn.config(state=tk.DISABLED)

    def _manage_selected_course(self):
        """Manage selected course"""
        selected_items = self.course_tree.selection()
        if not selected_items:
            messagebox.showwarning("Prompt", "Please select a course to manage first")
            return
            
        item_id = selected_items[0]
        course_id = self.course_tree.item(item_id, "values")[0]
        course = self.course_system.get_course_by_id(course_id)
        
        if course:
            self.show_course_detail(course)
        else:
            messagebox.showerror("Error", f"Course with ID {course_id} not found")

    def _delete_selected_course(self):
        """Delete selected course"""
        selected_items = self.course_tree.selection()
        if not selected_items:
            messagebox.showwarning("Prompt", "Please select a course to delete first")
            return
            
        item_id = selected_items[0]
        course_id = self.course_tree.item(item_id, "values")[0]
        course = self.course_system.get_course_by_id(course_id)
        
        if not course:
            messagebox.showerror("Error", f"Course with ID {course_id} not found")
            return
            
        if not messagebox.askyesno("Confirm Deletion", f"Are you sure you want to delete course '{course.CourseName}'? This operation cannot be undone!"):
            return
            
        try:
            success = self.course_system.DeleteCourse(course_id)
            if success:
                messagebox.showinfo("Suceess","Deletion Successful")
                self.refresh_courses()
                self.manage_course_btn.config(state=tk.DISABLED)
                self.delete_course_btn.config(state=tk.DISABLED)
            else:
                messagebox.showerror("Deletion Failed")
                
        except Exception as e:
            messagebox.showerror("Error", f"Error deleting course: {str(e)}")

    def refresh_courses(self):
        """Refresh course list"""
        # Clear existing data
        for item in self.course_tree.get_children():
            self.course_tree.delete(item)
            
        # Get and display all courses created by the teacher
        for course_id in self.teacher.Courses:
            course = self.course_system.get_course_by_id(course_id)
            if course:
                # Calculate student count
                student_count = len(self.course_system.GetStudentsInCourse(course.ID))
                
                # Add course to table
                self.course_tree.insert("", tk.END, values=(
                    course.ID,
                    course.CourseName,
                    course.CourseTime,
                    course.Classroom,
                    student_count
                ))

    def show_course_detail(self, course: Course):
        """Show course detail window"""
        CourseDetailWindow(
            self, course, self.teacher, self.course_system, self.user_system, self.assignment_system
        )

    def _create_new_course(self):
        """Create new course, including course description"""
        # Create course window
        create_window = tk.Toplevel(self)
        create_window.title("Create New Course")
        create_window.geometry("500x500")  # Increased height to accommodate description input
        
        # Form layout
        form_frame = ttk.Frame(create_window, padding="30 20 30 20")
        form_frame.pack(fill=tk.BOTH, expand=True)
        
        # Course ID
        ttk.Label(form_frame, text="Course ID:").grid(row=0, column=0, sticky=tk.W, pady=12)
        self.course_id_entry = ttk.Entry(form_frame, width=30)
        self.course_id_entry.grid(row=0, column=1, pady=12)
        
        # Course Name
        ttk.Label(form_frame, text="Course Name:").grid(row=1, column=0, sticky=tk.W, pady=12)
        self.course_name_entry = ttk.Entry(form_frame, width=30)
        self.course_name_entry.grid(row=1, column=1, pady=12)
        
        # Class Time
        ttk.Label(form_frame, text="Class Time:").grid(row=2, column=0, sticky=tk.W, pady=12)
        self.course_time_entry = ttk.Entry(form_frame, width=30)
        self.course_time_entry.grid(row=2, column=1, pady=12)
        
        # Classroom
        ttk.Label(form_frame, text="Classroom:").grid(row=3, column=0, sticky=tk.W, pady=12)
        self.classroom_entry = ttk.Entry(form_frame, width=30)
        self.classroom_entry.grid(row=3, column=1, pady=12)
        
        # Course Description (optional)
        ttk.Label(form_frame, text="Course Description (optional):").grid(row=4, column=0, sticky=tk.NW, pady=12)
        self.intro_text = scrolledtext.ScrolledText(
            form_frame, font=("Arial", 10), wrap=tk.WORD, height=6, width=30)
        self.intro_text.grid(row=4, column=1, pady=12, sticky=tk.NSEW)
        
        # Configure grid weights to make description input expandable
        form_frame.grid_rowconfigure(4, weight=1)
        form_frame.grid_columnconfigure(1, weight=1)
        
        # Button area
        btn_frame = ttk.Frame(create_window, padding="20 10 20 20")
        btn_frame.pack(fill=tk.X, side=tk.BOTTOM)
        
        # Confirm creation button
        confirm_btn = ttk.Button(
            btn_frame, text="Confirm Creation", command=lambda: self._confirm_create_course(create_window)
        )
        confirm_btn.pack(side=tk.RIGHT, padx=10)
        
        # Cancel button
        cancel_btn = ttk.Button(
            btn_frame, text="Cancel", command=create_window.destroy
        )
        cancel_btn.pack(side=tk.RIGHT)

    def _confirm_create_course(self, window):
        """Confirm creation of new course, including course description"""
        course_id = self.course_id_entry.get().strip()
        course_name = self.course_name_entry.get().strip()
        course_time = self.course_time_entry.get().strip()
        classroom = self.classroom_entry.get().strip()
        introduction = self.intro_text.get("1.0", tk.END).strip()  # Get course description
        
        # Validate required fields
        if not (course_id and course_name and course_time and classroom):
            messagebox.showerror("Error", "Please fill in all required fields!")
            return
            
        # Create course
        try:
            course = self.course_system.CreateCourse(
                ID=course_id,
                Teacher=self.teacher,
                CourseName=course_name,
                CourseTime=course_time,
                Classroom=classroom,
                Students=[],
                Assignments=[],
                introduction=introduction  # Pass course description
            )
            
            # Save teacher information
            messagebox.showinfo("Creation Successful", f"Course '{course_name}' created successfully!")
            window.destroy()
            self.refresh_courses()
            
        except Exception as e:
            messagebox.showerror("Error", f"Error creating course: {str(e)}")

    def back_to_main(self):
        """Return to main interface"""
        self.parent.geometry("900x600")
        self.app.ShowTeacherMainFrame()

class TeacherMainFrame(ttk.Frame):
    def __init__(self, parent: tk.Tk, app: "LMSApp", teacher: Teacher, user_system: UserSystem, course_system: CourseSystem, assignment_system: AssignmentSystem):
        super().__init__(parent, style="Main.TFrame")
        self.app = app
        self.teacher = teacher
        self.user_system = user_system
        self.course_system = course_system
        self.assignment_system = assignment_system
        self.parent = parent
        
        self.parent.geometry("900x600")
        
        # Top navigation bar
        top_nav = ttk.Frame(self, style="Card.TFrame", height=60)
        top_nav.pack(fill=tk.X)
        top_nav.pack_propagate(False)
        
        # Welcome message
        welcome_label = ttk.Label(
            top_nav, text=f"Welcome back, Teacher {teacher.EnglishName}", font=("Arial", 14, "bold")
        )
        welcome_label.pack(side=tk.LEFT, padx=20, pady=20)
        
        # Personal information button
        info_btn = ttk.Button(
            top_nav, text="Personal Information", command=self.show_teacher_info
        )
        info_btn.pack(side=tk.RIGHT, padx=10, pady=15)
        
        # Logout button
        logout_btn = ttk.Button(
            top_nav, text="Logout", command=self.logout
        )
        logout_btn.pack(side=tk.RIGHT, padx=20, pady=15)
        
        # Main function area
        main_frame = ttk.Frame(self, style="Main.TFrame")
        main_frame.pack(expand=True, fill=tk.BOTH, padx=50, pady=50)
        
        # Course management module
        course_module = ttk.Frame(main_frame, style="Card.TFrame", height=250)
        course_module.pack(fill=tk.BOTH, expand=True, pady=20)
        course_module.pack_propagate(False)
        
        ttk.Label(course_module, text="📚", font=("Arial", 40)).pack(pady=(20, 15))
        ttk.Label(course_module, text="Course Management", style="SubTitle.TLabel").pack(pady=(0, 15))
        ttk.Label(course_module, text=f"Total {len(teacher.Courses)} courses", style="Normal.TLabel").pack(pady=(0, 30))
        
        course_btn = ttk.Button(
            course_module, text="Enter Course Management", command=self.enter_course_module, style="Primary.TButton"
        )
        course_btn.pack(padx=30, fill=tk.X)

    def show_teacher_info(self):
        """Show teacher personal information"""
        TeacherInfoWindow(self, self.teacher)

    def enter_course_module(self):
        """Enter course management module"""
        self.app.SwitchFrame(
            lambda root, app: TeacherCourseModuleFrame(
                root, app, self.teacher, self.user_system, self.course_system, self.assignment_system
            )
        )

    def logout(self):
        """Logout"""
        if messagebox.askyesno("Confirm Logout", "Are you sure you want to logout?"):
            self.parent.destroy()

class LMSApp:
    def __init__(self, root: tk.Tk, teacher_id: str):
        self.root = root
        self.root.title("GT-OOP Management LMS - Teacher Side")
        self.root.resizable(True, True)
        self.current_frame: Optional[ttk.Frame] = None
        self.teacher: Optional[Teacher] = None
        
        # Initialize systems
        self._init_systems()
        
        # Load and validate teacher
        self._load_and_validate_teacher(teacher_id)
        
        # Set style and show main interface
        SetupStyle()
        self.ShowTeacherMainFrame()

    def _init_systems(self):
        """Initialize system components"""
        data_dir = os.path.join(project_root, "Data")
        os.makedirs(data_dir, exist_ok=True)
        
        self.user_system = UserSystem(os.path.join(data_dir, "UserAccount.json"))
        self.course_system = CourseSystem(os.path.join(data_dir, "Course.json"))
        self.assignment_system = AssignmentSystem(os.path.join(data_dir, "Assignment.json"), self.course_system, self.user_system)

    def _load_and_validate_teacher(self, teacher_id: str):
        """Load and validate teacher information"""
        self.teacher = self.user_system.get_user_by_id(teacher_id, role_filter=["Teacher"])
        
        if not self.teacher:
            messagebox.showerror("Login Failed", f"Teacher with ID {teacher_id} not found")
            self.root.destroy()
            sys.exit(1)

    def SwitchFrame(self, frame_class: callable):
        """Switch interface frames"""
        if self.current_frame:
            self.current_frame.destroy()
            
        self.current_frame = frame_class(self.root, self)
        self.current_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=20)

    def ShowTeacherMainFrame(self):
        """Show teacher main interface"""
        self.SwitchFrame(
            lambda root, app: TeacherMainFrame(
                root, app, self.teacher, self.user_system, self.course_system, self.assignment_system
            )
        )

# Program entry
if __name__ == "__main__":
    root = tk.Tk()
    app = LMSApp(root, "T001")  # Teacher ID
    root.mainloop()